package com.colin.jipay.taobao_hook;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ThreadUtils;
import com.colin.jipay.config.ActConst;
import com.colin.jipay.utils.LogUtil;
import com.colin.jipay.utils.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import de.robv.android.xposed.XC_MethodHook;
import de.robv.android.xposed.XposedBridge;
import de.robv.android.xposed.XposedHelpers;

/**
 * author    : colin
 * e-mail    : colin12138@gmail.com
 * date      : 2019/7/6 2:58
 * qq        : 1018294974
 */
public class QianNiuHook {
    //请求刷新方法的参数
    private static Object objReqRefreshParam;
    //刷新消息列表的对象
    private static Object objMsgListControl;
    //是否开始执行循环获取交易数据
    private static boolean isStartScheduleGetMsg = false;
    private static boolean isFirst = true;

    private static String userId = "0";

    public void hook(final Context context, ClassLoader classLoader) {
        /**
         * 勾住刷新消息列表的方法
         */
        XposedHelpers.findAndHookMethod("c8.Qfi"
                , classLoader
                , "a"
                , XposedHelpers.findClass("c8.Sfi", classLoader)
                , new XC_MethodHook() {
                    @Override
                    protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
                        super.beforeHookedMethod(param);

                        Object objParam = param.args[0];
                        int a = XposedHelpers.getIntField(objParam, "a");
                        String b = (String) XposedHelpers.getObjectField(objParam, "b");
                        String c = (String) XposedHelpers.getObjectField(objParam, "c");
                        Object d = XposedHelpers.getObjectField(objParam, "d");
                        Long e = (Long) XposedHelpers.getObjectField(objParam, "e");
                        Long f = (Long) XposedHelpers.getObjectField(objParam, "f");
                        objReqRefreshParam = objParam;
                        objMsgListControl = param.thisObject;
                        if (!isStartScheduleGetMsg) {
                            isStartScheduleGetMsg = true;
                            scheduleExecuGetTradeMsg();
                        }
                    }

                    @Override
                    protected void afterHookedMethod(MethodHookParam param) throws Throwable {
                        LogUtil.log("after");
                        super.afterHookedMethod(param);
                        Object obj = param.getResult();
                        List<?> messages = (List<?>) XposedHelpers.getObjectField(obj, "c");
//                         List newOrderList = new ArrayList();
//                         for (int i = 0;i<messages.size();i++){
                        Object objMsg = messages.get(0);
                        JSONObject msgJson = JSON.parseObject(JSON.toJSONString(objMsg));
                        LogUtil.log(msgJson.toString());
                        try {
                            //判断数据是系统消息，买家已付款，不是历史的消息，则进行获取新交易订单的方法
//                            String conversationId= (String) XposedHelpers.callMethod(objMsg,"getConversationId");
//                            if (conversationId.equals("custom_conversationCustomSystem")){
//                                String latestContent= (String) XposedHelpers.callMethod(objMsg,"getLatestContent");
//                                if (latestContent.contains("买家已付款")){
                            if (null == msgJson.getString("subMsgTypeName") || !"买家已付款".equals(msgJson.getString("subMsgTypeName")))
                                return;
                            String recentBizId = SPUtils.getInstance(userId).getString("recentBizId", "-");
                            String lastBizId = msgJson.getString("bizId");
                            if (recentBizId.equals(lastBizId))
                                return;
                            SPUtils.getInstance(userId).put("recentBizId", lastBizId);
                            String msgContent = msgJson.getString("msgContent");
                            Intent intent = new Intent();
                            intent.setAction(ActConst.TAOBAO_GETORDER);
                            intent.putExtra("bizId", msgJson.getString("bizId"));
                            intent.putExtra("payer", StringUtils.getTextCenter(msgContent, "买家ID:", "\","));
                            intent.putExtra("money", StringUtils.getTextCenter(msgContent, "金额: ", "元"));
                            context.sendBroadcast(intent);
                            LogUtil.log("sendOrder");
//                                }
//                            }
                        } catch (Exception e) {
                            LogUtil.log(e.getMessage());
                        }
//                             userId = msgJson.getString("userId");
//                             if (isFirst){
//                                 isFirst = false;
//                                 SPUtils.getInstance(userId).put("recentBizId",msgJson.getString("bizId"));
//                                 LogUtil.log("end");
//                                 return;
//                             }
//                             String recentBizId = SPUtils.getInstance(userId).getString("recentBizId","-");
//                             LogUtil.log(recentBizId);
//
//                             String lastBizId = msgJson.getString("bizId");
//                             LogUtil.log(lastBizId);
//                             if (lastBizId.equals(recentBizId)){
//                                 break;
//                             }
//                             newOrderList.add(objMsg);
//                             SPUtils.getInstance(userId).put("recentBizId",lastBizId);
//                         }

//                         if (newOrderList.size() == 0)
//                             return;
//                         for (Object object : newOrderList){
//                             JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(object));

//                         }

                    }
                });

        XposedHelpers.findAndHookMethod("c8.DVg", classLoader, "b", new XC_MethodHook() {
            @Override
            protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
                super.beforeHookedMethod(param);
                param.setResult(true);
            }

            @Override
            protected void afterHookedMethod(MethodHookParam param) throws Throwable {
                super.afterHookedMethod(param);
            }
        });

        XposedHelpers.findAndHookConstructor("c8.JXg"
                , classLoader
                , String.class
                , Class.class
                , Bundle.class
                , new XC_MethodHook() {
                    @Override
                    protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
                        super.beforeHookedMethod(param);
                    }

                    @Override
                    protected void afterHookedMethod(MethodHookParam param) throws Throwable {
                        super.afterHookedMethod(param);
                        Object obj = param.thisObject;
                        Class<? extends Fragment> clsTabFragment = (Class<? extends Fragment>) XposedHelpers.getObjectField(obj, "b");
                        String a = (String) XposedHelpers.getObjectField(obj, "a");
                    }
                });

    }


    /**
     * 间隔3s循环主动执行获取交易数据的方法
     */
    public static void scheduleExecuGetTradeMsg() {
        ThreadUtils.executeByFixedAtFixRate(4, new ThreadUtils.SimpleTask<Object>() {
            @Nullable
            @Override
            public Object doInBackground() throws Throwable {
                return null;
            }

            @Override
            public void onSuccess(@Nullable Object result) {
                XposedHelpers.callMethod(objMsgListControl, "a", objReqRefreshParam);
                XposedBridge.log("主动执行获取交易数据的方法");
            }
        }, 3, TimeUnit.SECONDS);
    }

    /**
     * 打开千牛日志
     */
    public static void hookSetLogOpen(ClassLoader classLoader) {

    }

    /**
     * hook到按tab键生成的fragment数据对象
     */
    public static void hookTabFragmentCreated(ClassLoader classLoader) {
//        Class<? extends Fragment> clsFrament=new Fragment().getClass();

    }

    /**
     * hook到首页的消息碎片页的数据刷新的方法
     */
    public static void hookMsgLVAdapterNotify(ClassLoader classLoader) {

    }
}
